package system

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"goravel/app/http/requests"
	"goravel/app/models/systemEntity"
	"goravel/app/models/userEntity"
)

type RoleController struct {
	//Dependent services
}

func NewRoleController() *RoleController {
	return &RoleController{
		//Inject services
	}
}

// Index 分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      分页查询
// @Description  分页查询
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleIndex
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/role [get]
func (r *RoleController) Index(ctx http.Context) http.Response {
	Roles := []systemEntity.Role{}
	queries := ctx.Request().Queries()
	res, err := httpfacade.NewResult(ctx).SearchByParams(queries, nil).ResultPagination(&Roles, "Permissions", "ButtonPermissions")
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", err.Error())
	}
	return res
}

// List 列表查询
// @Summary      列表查询
// @Description  列表查询
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleList
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/role/list [get]
func (r *RoleController) List(ctx http.Context) http.Response {
	Roles := []systemEntity.Role{}
	queries := ctx.Request().Queries()
	httpfacade.NewResult(ctx).SearchByParams(queries, map[string]interface{}{}).List(&Roles)
	return httpfacade.NewResult(ctx).Success("", Roles)
}

// Show 查询
// @Summary      查询
// @Description  查询
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleShow
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param id path int true "id"
// @Success 200 {string} json {}
// @Router       /api/role/{id} [get]
func (r *RoleController) Show(ctx http.Context) http.Response {
	id := ctx.Request().RouteInt("id")
	Role := systemEntity.Role{}
	facades.Orm().Query().Model(&systemEntity.Role{}).Where("id = ?", id).First(&Role)
	return httpfacade.NewResult(ctx).Success("", Role)
}

// Store 新增
// @Summary      新增
// @Description  新增
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleStore
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param RoleData body requests.RoleRequest true "数据"
// @Success 200 {string} json {}
// @Router       /api/admin/role [post]
func (r *RoleController) Store(ctx http.Context) http.Response {
	var RoleRequest requests.RoleRequest
	errors, err := ctx.Request().ValidateRequest(&RoleRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	Role := systemEntity.Role{}
	//todo add request values
	//SystemUserLevel = systemEntity.SystemUserLevel{
	//	Name:      SystemUserLevelRequest.Name,
	//	Money:     SystemUserLevelRequest.Money,
	//	Discount:  SystemUserLevelRequest.Discount,
	//	IsPay:     SystemUserLevelRequest.IsPay,
	//	IsForever: SystemUserLevelRequest.IsForever,
	//	Grade:     SystemUserLevelRequest.Grade,
	//	Image:     SystemUserLevelRequest.Image,
	//	Icon:      SystemUserLevelRequest.Icon,
	//	Explain:   SystemUserLevelRequest.Explain,
	//	ExpNum:    SystemUserLevelRequest.ExpNum,
	//}
	facades.Orm().Query().Model(&systemEntity.Role{}).Create(&Role)
	return httpfacade.NewResult(ctx).Success("创建成功", nil)
}

// Update
// @Summary      更新
// @Description  更新
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleUpdate
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param RoleData body requests.RoleRequest true "数据"
// @Success 200 {string} json {}
// @Router       /api/admin/role/{id} [put]
func (r *RoleController) Update(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	Role := systemEntity.Role{}
	facades.Orm().Query().Model(&systemEntity.Role{}).Where("id=?", id).Find(&Role)
	if Role.ID == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据不存在", "")
	}
	var RoleRequest requests.RoleRequest
	errors, err := ctx.Request().ValidateRequest(&RoleRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	//todo add request values
	//SystemUserLevel = systemEntity.SystemUserLevel{
	//	Name:      SystemUserLevelRequest.Name,
	//	Money:     SystemUserLevelRequest.Money,
	//	Discount:  SystemUserLevelRequest.Discount,
	//	IsPay:     SystemUserLevelRequest.IsPay,
	//	IsForever: SystemUserLevelRequest.IsForever,
	//	Grade:     SystemUserLevelRequest.Grade,
	//	Image:     SystemUserLevelRequest.Image,
	//	Icon:      SystemUserLevelRequest.Icon,
	//	Explain:   SystemUserLevelRequest.Explain,
	//	ExpNum:    SystemUserLevelRequest.ExpNum,
	//}
	facades.Orm().Query().Model(&systemEntity.Role{}).Where("id=?", id).Update(&Role)
	return httpfacade.NewResult(ctx).Success("修改成功", nil)
}

// Destroy 删除
// @Summary      删除
// @Description  删除
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleDestroy
// @Security ApiKeyAuth
// @Success 200 {string} json {}
// @Router       /api/admin/role/{id} [delete]
func (r *RoleController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	facades.Orm().Query().Model(&systemEntity.Role{}).Where("id=?", id).Delete(&systemEntity.Role{})
	return httpfacade.NewResult(ctx).Success("删除成功", nil)
}

// Option 选项
// @Summary      选项
// @Description  选项
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleOption
// @Security ApiKeyAuth
// @Success 200 {string} json {}
// @Router       /api/admin/role/option [get]
func (r *RoleController) Option(ctx http.Context) http.Response {
	Roles := []systemEntity.Role{}
	queries := ctx.Request().Queries()
	res, _ := httpfacade.NewResult(ctx).SearchByParams(queries, nil).List(&Roles)
	return res
}

// SyncPermissions 同步权限
// @Summary      选项
// @Description  选项
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleSyncPermissions
// @Security ApiKeyAuth
// @Param Data body requests.RoleSyncRequest true "数据"
// @Success 200 {string} json {}
// @Router       /api/role/sync_permissions [post]
func (r *RoleController) SyncPermissions(ctx http.Context) http.Response {
	var RoleSyncRequest requests.RoleSyncRequest
	errors, err := ctx.Request().ValidateRequest(&RoleSyncRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	Role := systemEntity.Role{}
	db := facades.Orm().Query()
	err_1 := db.Model(&systemEntity.Role{}).Where("id=?", RoleSyncRequest.RoleID).First(&Role)
	if err_1 != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "无效的角色标识", err.Error())
	}
	pers := []systemEntity.Permission{}
	p_ids := []any{}
	for _, v := range RoleSyncRequest.PermissionIDs {
		p_ids = append(p_ids, v)
	}
	db.Model(&systemEntity.Permission{}).WhereIn("id", p_ids).Find(&pers)
	db.Model(&Role).Association("Permissions").Clear()
	db.Model(&Role).Association("Permissions").Replace(&pers)
	btn_pers := []systemEntity.ButtonPermission{}
	btn_ids := []any{}
	for _, p := range RoleSyncRequest.BtnPermissionIDs {
		btn_ids = append(btn_ids, p)
	}
	db.Model(&systemEntity.ButtonPermission{}).WhereIn("id", btn_ids).Find(&btn_pers)
	db.Model(&Role).Association("ButtonPermissions").Clear()
	db.Model(&Role).Association("ButtonPermissions").Replace(&btn_pers)
	return httpfacade.NewResult(ctx).Success("同步成功", nil)
}

// SyncUserRoles 同步角色
// @Summary      选项
// @Description  选项
// @Tags         RoleController
// @Accept       json
// @Produce      json
// @Id RoleSyncUserRoles
// @Param Data body requests.UserRoleRequest true "数据"
// @Security ApiKeyAuth
// @Success 200 {string} json {}
// @Router       /api/user/sync_role [post]
func (r *RoleController) SyncUserRoles(ctx http.Context) http.Response {
	var UserRoleRequest requests.UserRoleRequest
	errors, err := ctx.Request().ValidateRequest(&UserRoleRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	user := userEntity.User{}
	user_id := UserRoleRequest.UserID
	Roles := []systemEntity.Role{}
	db := facades.Orm().Query()
	db.Model(&userEntity.User{}).Where("id=?", user_id).First(&user)
	role_ids := []any{}
	for _, role := range UserRoleRequest.Roles {
		role_ids = append(role_ids, role)
	}
	db.Model(&systemEntity.Role{}).WhereIn("id", role_ids).Find(&Roles)
	db.Model(&user).Association("Roles").Clear()
	db.Model(&user).Association("Roles").Replace(&Roles)
	return httpfacade.NewResult(ctx).Success("同步成功", nil)
}
